<?php
/**
 * Created by lzl
 * Date: 2021 2021/10/9
 * Time: 16:03
 */
namespace App\Forms;

use App\Models\UserGoodsBehavior;
use Illuminate\Database\Query\Builder;

class UserBehaviorForms extends BaseForm
{

    /**
     * @param $goods_id
     * @param $uid
     * @param $type
     * @return bool
     */
    public function checkBehavior($goods_id, $uid, $type)
    {
        return UserGoodsBehavior::where(compact('goods_id','uid', 'type'))->exists();
    }


    /**
     * @param $goods_id
     * @param $uid
     * @param $type
     * @return UserGoodsBehavior|\Illuminate\Database\Eloquent\Model|Integer
     */
    public function setBehavior($goods_id, $uid, $type)
    {
        if($type == UserGoodsBehavior::BROWSE){
            $this->deleteBehavior($goods_id, $uid, $type);
        }else{
            //取消收藏
            $check = UserGoodsBehavior::where(compact('goods_id','uid', 'type'))->first();
            if(filled($check)){
                return $check->delete();
            }
        }

        return UserGoodsBehavior::create(compact('goods_id','uid', 'type'));
    }


    public function deleteBehavior($goods_id, $uid, $type)
    {
       return UserGoodsBehavior::where(compact('goods_id','uid', 'type'))->delete();
    }


    /**
     * 批量删除
     * @param $ids
     * @param array $where
     * @return bool|null
     */
    public function deleteBehaviorIds($ids, $where = [])
    {
        return UserGoodsBehavior::whereIn('id', $ids)->where($where)->delete();
    }


    /**
     * @param $validated
     * @return mixed
     */
    public function getBehaviorList($validated)
    {
        $list = UserGoodsBehavior::where(function($q) use ($validated){
            /**
             * @var Builder $q
             */
            if(isset($validated['type']) && $validated['type']){
                $q->where('type', $validated['type']);
            }

            if(isset($validated['uid']) && $validated['uid'] ){
                $q->where('uid', $validated['uid']);
            }

            return $q;
        })->page($validated['page'], $validated['limit'])->orderBy('id','desc')->get();

        return $list;
    }
}